package com.entfrm.biz.system.manager;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.entfrm.biz.system.entity.Role;
import com.entfrm.biz.system.entity.User;
import com.entfrm.biz.system.entity.UserRole;
import com.entfrm.biz.system.service.RoleService;
import com.entfrm.biz.system.service.UserRoleService;
import com.entfrm.biz.system.service.UserService;
import com.entfrm.biz.system.vo.ResultVo;
import com.entfrm.biz.system.vo.UserVo;
import com.entfrm.core.base.api.R;
import com.entfrm.core.base.constant.CommonConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <h3>entfrm</h3>
 * <p>用户</p>
 *
 * @author : kyc
 * @date : 2020-08-12 22:01
 **/
@Component
@PropertySource(value = "classpath:config.properties")
public class UserManager {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;


    /**
     * it维修员角色code
     */
    @Value("${repair.itServiceCode}")
    private String itServiceCode;

    /**
     * 查询it维修员列表
     */
    public List<UserVo> listServiceUser() {
        return userService.listUserByRoleCode(itServiceCode);
    }

    /**
     * 查询用户信息以及角色列表
     */
    public R getUserById(Integer id) {
        User user = userService.getById(id);
        List<Integer> roles = new ArrayList<>();
        List<Role> roleList = roleService.list(new QueryWrapper<Role>().lambda().eq(Role::getStatus, CommonConstants.Status.NO));
        if (user != null) {
            roles = userRoleService.list(new QueryWrapper<UserRole>().eq("user_id", user.getId()))
                    .stream().map(userRole -> userRole.getRoleId()).collect(Collectors.toList());

            user.setRoles(ArrayUtil.toArray(roles, Integer.class));
        }
        return R.ok(ResultVo.builder().result(user).extend(roleList).build());
    }
}
